HTMLTextAreaElement: selectionchange イベント

Baseline 2024
Newly available

Since September 2024, this feature works across the latest devices and browser versions. This feature might not work in older devices or browsers.

selectionchange選択 API のイベントで、<textarea> 要素内のテキストの選択状態が変更されたときに発生します。 これは、文字の選択範囲の変更と、キャレットが移動した場合の両方を含みます。

このイベントはキャンセル不可です。

イベントは通常 <textarea> にイベントリスナーを追加することで処理され、HTMLTextAreaElement で読み込まれるハンドラー関数で処理されます。selectionStartselectionEndselectionDirection プロパティで読み取ります。

グローバルな onselectionchange イベントハンドラーにリスナーを追加し、ハンドラー関数内で Document.getSelection() を使用して Selection を取得することも可能です。しかし、これは テキスト の選択範囲の変更を取得するのにはあまり有益ではありません。

構文

このイベント名を addEventListener() などのメソッドで使用するか、イベントハンドラープロパティを設定するかしてください。

js
addEventListener("selectionchange", (event) => { })

onselectionchange = (event) => { }

イベント型

一般的な Event です。

下記の例では、<textarea> 要素内での選択範囲を取得する方法を紹介します。

HTML

html
<div>
  ここにテキストを入力して選択してください:<br /><textarea
    id="my-text"
    rows="2"
    cols="20"></textarea>
</div>
<div>selectionStart: <span id="start"></span></div>
<div>selectionEnd: <span id="end"></span></div>
<div>selectionDirection: <span id="direction"></span></div>

JavaScript

js
const myInput = document.getElementById("my-text");

myInput.addEventListener("selectionchange", () => {
  document.getElementById("start").textContent = myInput.selectionStart;
  document.getElementById("end").textContent = myInput.selectionEnd;
  document.getElementById("direction").textContent = myInput.selectionDirection;
});

仕様書

Specification
Selection API
# selectionchange-event
Selection API
# dom-globaleventhandlers-onselectionchange